package com.ncmem.up7.database.sql;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ncmem.model.FileInf;
import com.ncmem.up7.database.oracle.OracleFolder;
import com.ncmem.up7.sql.*;
import com.ncmem.utils.ConfigReader;
import com.ncmem.utils.DataBaseType;
import com.ncmem.utils.PathTool;
import org.apache.commons.lang.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class SqlFolder {

    public static SqlFolder build(){

        if( ConfigReader.dbType() == DataBaseType.SqlServer ) return new SqlFolder();
        //else if( ConfigReader.dbType() == DataBaseType.MySQL ) return new MySQLFolder();
        else if( ConfigReader.dbType() == DataBaseType.Oracle ||
                ConfigReader.dbType() == DataBaseType.DMDB ) return new OracleFolder();
        //else if( ConfigReader.dbType() == DataBaseType.KingBase ) return new OdbcFolder();
        //else if( ConfigReader.dbType() == DataBaseType.MongoDB ) return new DbFolderMongodb();
        return new SqlFolder();
    }

    //根节点
    JSONObject root ;//= new JObject { { "f_id", "" }, { "f_nameLoc", "根目录" }, { "f_pid", "" }, { "f_pidRoot", "" },{ "f_pathRel",""} };

    public SqlFolder() {
        this.root = new JSONObject();
        this.root.put("f_id", "");
        this.root.put("f_nameLoc", "根目录");
        this.root.put("f_pid", "");
        this.root.put("f_pidRoot", "");
        this.root.put("f_pathRel", "");
    }

    public SqlTable table(){
        return  SqlTable.build("up7_folders");
    }

    public Map<String, JSONObject> toDic(JSONArray folders)
    {
        Map<String, JSONObject> dt = new HashMap<String, JSONObject>();
        for(int i = 0 , l = folders.size();i<l;++i)
        {
            JSONObject o = folders.getJSONObject(i);
            String id = o.getString("f_id");
            dt.put(id, o);
        }
        return dt;
    }

    /// <summary>
    /// 构建路径
    /// </summary>
    /// <param name="fd"></param>
    /// <returns></returns>
    public String build_path(JSONObject fdCur)
    {
        String id = fdCur.getString("id").trim();
        String pid = fdCur.getString("pid").trim();
        String pathRel = fdCur.getString("pathRel").trim();
        List<FileInf> rels = new ArrayList<FileInf>();

        //根目录
        if (pathRel=="/")
        {
            FileInf f = new FileInf();
            f.pathSvr = "/";
            f.nameLoc = "根目录";
            rels.add(f);

            FileInf dir = new FileInf();
            dir.pathRel = pathRel;
            int rpos = dir.pathRel.lastIndexOf("/");
            dir.nameLoc = dir.pathRel.substring(rpos + 1);
            rels.add(dir);
        }
        //子目录
        else {
            // /a/b/c/d/e=>,a,b,c,d,e
            int pos = 0;
            while ( (pos = pathRel.indexOf("/", pos)) !=-1)
            {
                FileInf dir = new FileInf();
                dir.pathRel = pathRel.substring(0, pos);
                dir.nameLoc = PathTool.getName(dir.pathRel);
                if (StringUtils.isEmpty(dir.nameLoc)) dir.nameLoc = "根目录";
                if (StringUtils.isEmpty(dir.pathRel)) dir.pathRel = "/";
                rels.add(dir);
                pos++;
            }
            FileInf f = new FileInf();
            f.pathRel = pathRel;
            f.nameLoc = PathTool.getName(f.pathRel);
            rels.add(f);
        }
        return new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create().toJson(rels);
    }

    /**
     * 检查是否存在同名目录
     * @param pathRel
     * @return
     */
    public Boolean exist_same_folder(String pathRel)
    {
        SqlWhereMerge swm = new SqlWhereMerge();
        swm.equal("f_pathRel", pathRel);
        swm.equal("f_deleted", 0);
        String where = swm.to_sql();

        String sql = String.format("(select f_id from up7_files where %s ) union (select f_id from up7_folders where %s)", where,where);

        SqlExec se = new SqlExec();
        JSONArray fid = se.exec("up7_files", sql, "f_id", "");
        return fid.size() > 0;
    }

    public static boolean existSameFolder(String name,String pid)
    {
        SqlExec se = new SqlExec();

        //子目录
        if(StringUtils.isEmpty(pid))
        {
            return se.count("up7_folders",new SqlParam[] {
                    new SqlParam("f_nameLoc",name),
                    new SqlParam("f_pid",pid),
                    new SqlParam("f_deleted",false)
            })>0;
        }//根目录
        else
        {
            return se.count("up7_files",new SqlParam[] {
                    new SqlParam("f_nameLoc",name),
                    new SqlParam("f_pid",pid),
                    new SqlParam("f_deleted",false)
            })>0;
        }
    }


    public static String getPathRel(String id)
    {
        SqlExec se = new SqlExec();
        JSONObject ret = se.read("up7_files", "f_pathRel", new SqlParam[] { new SqlParam("f_id", id) });
        if( !ret.has("f_pathRel") )
            ret = se.read("up7_folders", "f_pathRel", new SqlParam[] { new SqlParam("f_id", id) });
        return ret.getString("f_pathRel");
    }

    /**
     * 更新子文件路径
     * @param pathRelOld
     * @param pathRelNew
     */
    public void updatePathRel(String pathRelOld,String pathRelNew)
    {
        //更新子文件路径
        String sql = String.format("update up7_folders set f_pathRel=REPLACE(f_pathRel,'%s/','%s/') where CHARINDEX('%s/',f_pathRel)=1",
                pathRelOld,
                pathRelNew,
                pathRelOld
        );

        SqlExec se = new SqlExec();
        se.exec(sql);
    }

    public FileInf read(String id) throws ParseException, IllegalAccessException, SQLException {
        return this.table().readOne(FileInf.build(),
                SqlWhere.build().eq("f_id",id));
    }

    /**
     * 取同名目录信息
     * @param pathRel
     * @param id
     * @return
     */
    public FileInf read(String pathRel, String id) throws ParseException, IllegalAccessException, SQLException {
        return this.table().readOne(FileInf.build(),
                SqlWhere.build().eq("f_pathRel",pathRel)
                        .eq("f_deleted",false)
                        .ineq("f_id",id));
    }

    public void complete(String id) throws ParseException, IllegalAccessException, SQLException {
        this.table().update(
                SqlSeter.build().set("f_complete",true),
                SqlWhere.build().eq("f_id",id)
        );
    }

    public void del(String id,String uid) throws ParseException, IllegalAccessException, SQLException {
        this.table().update(
                SqlSeter.build().set("f_deleted",true),
                SqlWhere.build()
                        .eq("f_id",id)
                        .eq("f_uid",uid)
        );
    }

    public void add(FileInf dir) throws ParseException, IllegalAccessException, SQLException {
        this.table().insert(dir);
    }

    //批量添加
    public void addBatch(List<FileInf> arr) throws SQLException, ParseException, IllegalAccessException {
        this.table().inserts(arr);
    }
}
